package com.tange.ai.core.sample.binding

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import com.tange.ai.core.sample.databinding.ActivityBindingQrCodeBinding
import com.tange.ai.core.sample.utils.Utils
import com.tange.base.toolkit.Tips
import com.tange.base.ui.design.BasicDialogLoading
import com.tange.base.ui.design.BasicDialogRequest
import com.tange.feature.binding.qrcode.DeviceBindingQrcode
import com.tange.feature.binding.query.DeviceBindingQuery
import com.tg.appcommon.android.TGLog

class BindingQrcodeActivity: AppCompatActivity() {

    companion object {
        const val TAG = "BindingQrcodeActivity_"
        const val CONFIG_REQ_CODE = 1001
    }

    private lateinit var binding: ActivityBindingQrCodeBinding

    private var bindingQuery: DeviceBindingQuery? = null

    private var loading: BasicDialogLoading? = null

    private var bindingConfiguration = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityBindingQrCodeBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
        }

        Utils.setStatusBar(this, Color.TRANSPARENT)

        binding.queryMatching.setOnClickListener {
            query()
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 100)
        }

        startActivityForResult(Intent(this, BindingConfigureActivity::class.java), CONFIG_REQ_CODE)
    }

    private fun query() {
        if (loading?.isShowing == true) {
            loading?.dismiss()
        }

        loading = BasicDialogLoading(this).apply {
            setMessage("查询设备的绑定状态...")
        }
        loading?.show()


        bindingQuery?.stop()
        bindingQuery = DeviceBindingQuery()
        bindingQuery?.duration = 120 * 1000L
        bindingQuery?.start(bindingConfiguration) {
            loading?.dismiss()

            if (it.success) {
                BasicDialogRequest(this@BindingQrcodeActivity).apply {
                    setMessage("绑定成功： 设备ID=${it.data}")
                    setPositiveText("知道了")
                    setPositiveOnClicked {
                        dismiss()
                        finish()
                    }
                }.show()
            } else {
                BasicDialogRequest(this@BindingQrcodeActivity).apply {
                    setMessage("绑定失败： ${it.code}, ${it.message}")
                    setPositiveText("知道了")
                    setPositiveOnClicked {
                        dismiss()
                        finish()
                    }
                }.show()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == BindingBluetoothScanActivity.CONFIG_REQ_CODE && RESULT_CANCELED == resultCode) {
            Tips.show("必须生成绑定配置信息")
            finish()
            return
        }

        if (requestCode == CONFIG_REQ_CODE) {
            if (RESULT_OK == resultCode) {
                bindingConfiguration = data?.getStringExtra(BindingConfigureActivity.CONFIG) ?: ""
                TGLog.i(TAG, "[onActivityResult] $bindingConfiguration")
                if (TextUtils.isEmpty(bindingConfiguration)) {
                    finish()
                } else {
                    createQrcode()
                }
            } else{
                finish()
            }
        }
    }

    private fun createQrcode() {
        if (TextUtils.isEmpty(bindingConfiguration)) {
            Toast.makeText(this, "绑定配置信息为空！", Toast.LENGTH_LONG).show()
            return
        }

        val width = binding.qrCodeIv.measuredWidth
        val height = binding.qrCodeIv.measuredHeight

        DeviceBindingQrcode.create(bindingConfiguration, width, height)?.let {
            binding.qrCodeIv.setImageBitmap(it)
        }

    }
}